package com.youlu.campus.web.sys.impl;

import com.youlu.campus.service.base.BaseService;
import com.youlu.campus.web.config.aspect.UseCache;
import com.youlu.campus.web.sys.SysConfigService;
import com.youlu.campus.web.sys.po.SysConfigEnum;
import com.youlu.campus.web.sys.po.SysConfigPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zgz
 * @date 2020/3/14 10:13
 */
@Slf4j
@Service
public class SysConfigServiceImpl extends BaseService implements SysConfigService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String getConfigByKey(SysConfigEnum configEnum) {
        List<String> configs = this.getConfigListByKey(configEnum);
        if (!CollectionUtils.isEmpty(configs)) {
            return configs.get(0);
        }
        return configEnum.getDefaultValue();
    }

    @Override
    @UseCache(expireTime = 5, timeUnit = TimeUnit.MINUTES)
    public Integer getConfigByKeyForInt(SysConfigEnum configEnum) {
        String value = configEnum.getDefaultValue();
        List<String> configs = this.getConfigListByKey(configEnum);
        if (!CollectionUtils.isEmpty(configs)) {
            value = configs.get(0);
        }
        return Integer.valueOf(value);
    }

    @Override
    public List<String> getConfigListByKey(SysConfigEnum configEnum) {
        List<SysConfigPO> configPOS = this.getSysConfigList(configEnum);
        return configPOS.stream().map(x -> x.getValue()).collect(Collectors.toList());
    }

    @Override
    public List<SysConfigPO> getSysConfigList(SysConfigEnum configEnum) {
        Query query = new Query();
        query.addCriteria(Criteria.where("deleted").is(false));
        query.addCriteria(Criteria.where("key").is(configEnum.getKey()));
        if (StringUtils.isNotBlank(configEnum.getSecondKey())) {
            query.addCriteria(Criteria.where("secondKey").is(configEnum.getSecondKey()));
        }
        List<SysConfigPO> configPOS = mongoTemplate.find(query, SysConfigPO.class);
        return configPOS;
    }

    @Override
    @UseCache(expireTime = 1, timeUnit = TimeUnit.MINUTES)
    public SysConfigPO getSysConfig(SysConfigEnum configEnum) {
        List<SysConfigPO> configPOS = this.getSysConfigList(configEnum);
        if (!CollectionUtils.isEmpty(configPOS)) {
            return configPOS.get(0);
        }
        return null;
    }
}
